﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.AspNetCore;
using System.ComponentModel;

namespace cmdb.keede.com
{
    public static class HtmlExtentions
    {
        public static IEnumerable<SelectListItem> GetEnumDescriptionSelectList<T>(this IHtmlHelper htmlHelper)
        {
            var modelType = typeof(T);
            var metadataForType = htmlHelper.MetadataProvider.GetMetadataForType(modelType);
            if (!metadataForType.IsEnum || metadataForType.IsFlagsEnum)
                throw new ArgumentException("T must be Enum type!");

            var type = typeof(T);
            var names= Enum.GetNames(type);

            return (from name in names
                let field = type.GetField(name)
                let attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false) as DescriptionAttribute
                select new SelectListItem
                {
                    Text = attr?.Description,
                    Value = name
                }).ToList();
        }
    }
}
